package tree;

/**
 * @author way
 * @create 2025-02-11 13:42
 */
public class _110_isBalanced2 {
    public boolean isBalanced(TreeNode root) {
        if (root == null) return true;

        return getHeight(root) >= 0;
    }

    private int getHeight(TreeNode root) {
        if (root == null) return 0;

        int leftHeight = getHeight(root.left);
        if (leftHeight == -1) return -1;
        int rightHeight = getHeight(root.right);
        if (rightHeight == -1) return -1;
        if (Math.abs(leftHeight - rightHeight) > 1) {
            return -1;
        } else {
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }
}
